<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="教材名称" prop="teachingMaterialName">
        <el-input
            v-model="queryParams.teachingMaterialName"
            placeholder="请输入教材名称"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="无人机类型" prop="uavType">
        <el-input
            v-model="queryParams.uavType"
            placeholder="请输入无人机类型"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="无人机型号" prop="uavNum">
        <el-input
            v-model="queryParams.uavNum"
            placeholder="请输入无人机型号"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['uav:material:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['uav:material:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['uav:material:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            :loading="exportLoading"
            @click="handleExport"
            v-hasPermi="['uav:material:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="materialList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="教材名称" align="center" prop="teachingMaterialName" />
      <el-table-column label="无人机类型" align="center" prop="uavType" />
      <el-table-column label="无人机型号" align="center" prop="uavNum" />
      <el-table-column label="教材类型" align="center" prop="teachingMaterialType">
        <template slot-scope="scope">
          <el-tag>
            {{scope.row.teachingMaterialInfo.split('.')[1]}}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="是否启用" align="center" prop="permission"  v-if="checkRole(['admin','teacher'])">
        <template slot-scope="scope">
          <el-switch
              v-model="scope.row.permission"
              active-value="1"
              inactive-value="0"
              @change="(value)=>onChangePermission(value, scope.row)"
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              v-hasPermi="['uav:material:preview']"
              @click="preview(scope.row.teachingMaterialInfo)"
          >
            预览
          </el-button>
          <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['uav:material:edit']"
          >修改</el-button>
          <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['uav:material:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改教材信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="教材名称" prop="teachingMaterialName">
          <el-input v-model="form.teachingMaterialName" placeholder="请输入教材名称" />
        </el-form-item>
        <el-form-item label="教材信息" prop="teachingMaterialInfo">
          <file-upload
              :limit="1"
              :fileSize="100"
              v-model="form.teachingMaterialInfo"
              :fileType="['png', 'jpg', 'jpeg', 'doc', 'docx','pdf','xls', 'xlsx', 'mp4']"
          ></file-upload>
        </el-form-item>
        <el-form-item label="无人机类型" prop="uavType">
          <el-input v-model="form.uavType" placeholder="请输入无人机类型" />
        </el-form-item>
        <el-form-item label="无人机型号" prop="uavNum">
          <el-input v-model="form.uavNum" placeholder="请输入无人机型号" />
        </el-form-item>
        <el-form-item label="是否启用" prop="permission">
          <el-switch
              v-model="form.permission"
              active-value="1"
              inactive-value="0"
          >
          </el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="预览教材" :visible.sync="isView" append-to-body fullscreen destroy-on-close @closed="loadingRender = true">
      <div
        v-loading="loadingRender"
        element-loading-text="拼命加载中"
        element-loading-spinner="el-icon-loading"
        style="width: 100%;height: calc(100vh - 117px)"
      >
        <el-image
          v-if="['jpg', 'jpeg', 'png'].includes(previewFile.type)"
          :src="previewFile.url"
          fit="contain"
          @load="renderedHandler"
          @error="errorHandler"
        ></el-image>
        <vue-office-pdf
          style="height: 100%;"
          v-if="['pdf'].includes(previewFile.type)"
          :src="previewFile.url"
          @rendered="renderedHandler"
          @error="errorHandler"
        />
        <vue-office-docx
          style="height: 100%;"
          v-if="['doc', 'docx'].includes(previewFile.type)"
          :src="previewFile.url"
          @rendered="renderedHandler"
          @error="errorHandler"
        />
        <vue-office-excel
          style="height: 100%;"
          v-if="['xls', 'xlsx'].includes(previewFile.type)"
          :src="previewFile.url"
          @rendered="renderedHandler"
          @error="errorHandler"
        />
        <video
          @loadeddata="loadingRender = false"
          style="width: 500px; margin: auto;"
          v-if="['mp4'].includes(previewFile.type)"
          controls
        >
          <source :src="previewFile.url" type="video/mp4">
        </video>
      </div>

    </el-dialog>
  </div>
</template>

<script>
// pdf
import VueOfficePdf from '@vue-office/pdf'
// docx
import VueOfficeDocx from '@vue-office/docx'
import '@vue-office/docx/lib/index.css'
// excel
import VueOfficeExcel from '@vue-office/excel'
import '@vue-office/excel/lib/index.css'

import { listMaterial, getMaterial, delMaterial, addMaterial, updateMaterial, exportMaterial } from "@/api/teach/textbook";
import {registerUeEvent} from "@/utils/ue/ueUtil";
import { checkRole } from "@/utils/permission";

export default {
  name: "Material",
  components: {VueOfficePdf, VueOfficeDocx, VueOfficeExcel},
  data() {
    return {
      loadingRender: true,
      previewFile: {
        url: '',
        type: ''
      },
      isView: false,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 教材信息表格数据
      materialList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        teachingMaterialName: null,

        teachingMaterialInfo: null,

        uavType: null,

        uavNum: null,

        teachingMaterialType: null,

        permission: null,

      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        teachingMaterialName: [
            { required: true, message: '请输入教材名称', trigger: 'blur' }
        ],
        teachingMaterialInfo: [
          { required: true, message: '请上传教材', trigger: 'blur' }
        ],
        uavType: [
          { required: true, message: '请选择无人机类型', trigger: 'blur' }
        ],
        uavNum: [
          { required: true, message: '请输入无人机型号', trigger: 'blur' }
        ],
      }
    };
  },
  created() {
    this.getList();
    registerUeEvent('add', (data)=>{
      console.log(data)
      alert(JSON.stringify(data))
    })
  },
  methods: {
    checkRole,
    renderedHandler(){
      this.loadingRender = false
    },
    errorHandler(){
      alert('文件加载失败，请重试')
    },
    // 预览文件
    preview(fileUrl){
      this.isView = true
      const arr = fileUrl.split('.')
      const type = arr[arr.length - 1]
      this.previewFile = {
        url: process.env.VUE_APP_BASE_API + fileUrl,
        type: type
      }

    },
    // 是否启用被改变
    onChangePermission(value, row){
      updateMaterial(row).then(response => {
        this.$modal.msgSuccess("修改成功");
        this.open = false;
        this.getList();
      });
    },
    /** 查询教材信息列表 */
    getList() {
      this.loading = true;
      listMaterial(this.queryParams).then(response => {
        this.materialList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        teachingMaterialId: null,

        teachingMaterialName: null,

        teachingMaterialInfo: null,

        uavType: null,

        uavNum: null,

        teachingMaterialType: null,

        permission: null,

        createBy: null,

        createTime: null,

        updateBy: null,

        updateTime: null,

      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.teachingMaterialId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加教材信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const teachingMaterialId = row.teachingMaterialId || this.ids
      getMaterial(teachingMaterialId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改教材信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.teachingMaterialId != null) {
            updateMaterial(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMaterial(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const teachingMaterialIds = row.teachingMaterialId || this.ids;
      this.$modal.confirm('是否确认删除教材信息编号为"' + teachingMaterialIds + '"的数据项？').then(function() {
        return delMaterial(teachingMaterialIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$modal.confirm('是否确认导出所有教材信息数据项？').then(() => {
        this.exportLoading = true;
        return exportMaterial(queryParams);
      }).then(response => {
        this.$download.name(response.msg);
        this.exportLoading = false;
      }).catch(() => {});
    }
  }
};
</script>
